import React, {useEffect, useState} from "react";
import {connect, Link} from "umi";
import {Button, Flex, Modal, Pagination, Rate, Space, Table} from "antd";

import style from "@/pages/users/index.css";
import CourseModal from "@/pages/course/components/CourseModal";
import Comments from './components/comment'

const Course = (props) => {
  const {roleId, userInfo} = props.location.state
  const {course: {courseList, total, commentList, scoreMap, applied}, dispatch} = props

  const [currentPage, setCurrentPage] = useState(1)
  const [record, setRecord] = useState(undefined)
  const [photo, setPhoto] = useState(undefined)
  const [visible, setVisible] = useState(false)
  const [open, setOpen] = useState(false);
  const [content, setContent] = useState('')

  useEffect(() => {
    dispatch({
     type: 'course/getCourseByPage',
     payload: {
       pageNum: 1,
       pageSize: 5,
     },
    })
  }, [])

  const columns = [
    {
      title: '课程图片',
      dataIndex: 'photo',
      key: 'photo',
      render: text => (
        <img src={text} width="50" height="50"/>
      )
    },
    {
      title: '课程名',
      dataIndex: 'courseName',
      key: 'courseName',
      render: text => <a>{text}</a>,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '评分',
      dataIndex: 'score',
      key: 'score',
      render: (text, record) => (
        <div>
          <Flex gap="small">
            <Rate allowHalf={true} disabled={scoreMap[record.id] === 1 ? true : false}  value={text} onChange={handleMark} onFocus={() => setRecord(record)} />
            <Space>
              <a>{text}分</a>
              <a>{scoreMap[record.id] === 1 ? "(已评分)" : ""}</a>
            </Space>
          </Flex>
        </div>
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <div>
          <Flex gap="small">
            <Button style={{display: roleId !== 42 ? 'none' : ''}} type="primary" size="small" onClick={() => editHandler(record)}>修改</Button>
            <Button style={{display: roleId !== 42 ? 'none' : ''}} hidden={roleId !== 42} type="danger" size="small" onClick={() => showConfirm(record)}  className={style.delete}>删除</Button>
            <Button size="small" onClick={() => showDrawer(record)}>评论</Button>
            {applied.includes(record.id)
              ? (<Button style={{display: roleId !== 40 ? 'none' : '', backgroundColor: '#fd726f'}} size="small" type="primary" onClick={() => disApplySysCourse(record)}>取消报名</Button>)
              : <Button style={{display: roleId !== 40 ? 'none' : ''}} size="small" className={style.add} onClick={() => applySysCourse(record)}>报名</Button>}
            <Comments open={open} userInfo={userInfo} commentList={commentList} onClose={onClose} content={content} setContent={setContent} handlePublish={handlePublish} handleDelete={handleDelete} />
          </Flex>
        </div>
      ),
    },
  ];

  const disApplySysCourse = (record) => {
    confirm({
      content: `你确定要取消报名这个课程吗`,
      onOk() {
        dispatch({
          type: 'course/disApplySysCourse',
          payload: {courseId: record.id},
        }).then(() => {
          dispatch({
            type: 'course/getCourseByPage',
            payload: {
              pageNum: currentPage,
              pageSize: 5,
            },
          })
        })
      },
      onCancel() {},
      okText: '确定',
      cancelText: '取消',
    })
  }

  const applySysCourse = (record) => {
    confirm({
      content: `你确定要报名这个课程吗`,
      onOk() {
        dispatch({
          type: 'course/applySysCourse',
          payload: {
            courseId: record.id,
          }
        }).then(() => {
          dispatch({
            type: 'course/getCourseByPage',
            payload: {
              pageNum: currentPage,
              pageSize: 5,
            },
          })
        })
      },
      onCancel() {},
      okText: '确定',
      cancelText: '取消',
    })
  }

  const handleMark = (value) => {
    dispatch({
      type: 'course/markSubmit',
      payload: {
        courseId: record.id,
        courseName: record.name,
        score: value,
      }
    }).then(() => {
      dispatch({
        type: 'course/getCourseByPage',
        payload: {
          pageNum: currentPage,
          pageSize: 5,
        },
      })
    })
  }

  const handleDelete = (commentId) => {
    dispatch({
      type: 'course/deleteComment',
      payload: {
        commentId: commentId
      },
    }).then(() => {
      dispatch({
        type: 'course/getComments',
        payload: {
          courseId: record.id,
          userId: 11,
        }
      })
    })
  }

  const handlePublish = () => {
    setContent('')
    dispatch({
      type: 'course/publishComment',
      payload: {
        courseId: record.id,
        userId: userInfo.id,
        name: userInfo.name,
        description: content,
      }
    }).then(() => {
      dispatch({
        type: 'course/getComments',
        payload: {
          courseId: record.id,
          userId: userInfo.id,
        }
      })
    })
  }

  const showDrawer = (record) => {
    dispatch({
      type: 'course/getComments',
      payload: {
        courseId: record.id,
        userId: userInfo.id,
      }
    })
    setRecord(record)
    setOpen(true);
  };

  const onClose = () => {
    setOpen(false);
    setContent('')
  };

  const { confirm } = Modal;

  const showConfirm = (record) => {
    confirm({
      content: '你确定要删除这个课程吗？',
      onOk() {
        dispatch({
          type: 'course/deleteCourse',
          payload: {
            courseId: record.id
          },
        }).then(() => {
          dispatch({
            type: 'course/getCourseByPage',
            payload: {
              pageNum: currentPage,
              pageSize: 5,
            },
          })
        })
      },
      onCancel() {},
      okText: '确定',
      cancelText: '取消',
      centered: true,
    });
  }

  const editHandler = (record) => {
    setVisible(true)
    setRecord(record)
  }

  const addHandler = () => {
    setVisible(true)
    setRecord(undefined)
  }

  const onChange = (page) => {
    setCurrentPage(page)
    dispatch({
      type: 'course/getCourseByPage',
      payload: {
        pageNum: page,
        pageSize: 5,
      }
    })
  }

  const closeHandler = () => {
    setVisible(false)
  }

  const onFinish = (values) => {
    let id = 0
    if(record) {
      id = record.id
    }
    if(id) {
      dispatch({
        type: 'course/updateCourse',
        payload: {
          id,
          courseName: values.courseName,
          photo: photo,
        },
      })
        .then(() => {
          setVisible(false)
          dispatch({
            type: 'course/getCourseByPage',
            payload: {
              pageNum: 1,
              pageSize: 5,
            }
          })
        })
    }else {
      dispatch({
        type: 'course/addCourse',
        payload: {
          courseName: values.courseName,
          photo: photo,
        },
      })
        .then(() => {
        setVisible(false)
        dispatch({
          type: 'course/getCourseByPage',
          payload: {
            pageNum: 1,
            pageSize: 5,
          }
        })
      })
    }
  }

  return (
    <div style={{height: "100%"}}>
      <div>
        {/*<div style={{textAlign: "center",fontSize: "35px" , marginBottom: "10px", height: "75px", width: "100%", background: "#fff", padding: "10px", border: "1px solid #ebeef5", borderRadius: "3px"}}>
          课程管理界面
        </div>*/}
        <div hidden={roleId !== 42} style={{margin: "10px 0", width: "100%", background: "#fff", padding: "10px", border: "1px solid #ebeef5", borderRadius: "3px"}}>
          <Button className={style.add} onClick={() => addHandler()}>添加</Button>
        </div>
        <div>
          <Table rowKey={record => record.id} columns={columns} dataSource={courseList} pagination={false}/>
        </div>
        <div>
          <CourseModal visible={visible} onFinish={onFinish} closeHandler={closeHandler} setPhoto={setPhoto}/>
        </div>
        <div style={{marginTop: "10px"}}>
          <Pagination current={currentPage} onChange={onChange} total={total} pageSize={5} />
        </div>
      </div>
    </div>
  )
}

const mapStateToProps = ({course}) => {
  return {
    course,
  }
}

export default connect(mapStateToProps)(Course)
